/* eslint-disable react-hooks/exhaustive-deps */
import React, { useEffect, useReducer, Fragment } from "react";
import {
  Button,
  Modal,
  Input,
  Form,
  Col,
  Row,
  Tree,
  Checkbox,
  message,
  Popconfirm,
} from "antd";
import { formatDate } from "../../util/tool";
import { DownOutlined, DeleteOutlined, CopyOutlined } from "@ant-design/icons";
import styles from "./index.module.scss";
import config from "../../configs/index";
import { delRole, updateRole, getSetting, setSetting } from "../../api/serve";
import { string } from "prop-types";
import { connect } from "react-redux";
const initState = {
  data: "",
  isModalOpen: false,
  id: "",
};

function adminRedcuer(state = initState, action) {
  if (action) {
    return { ...state, ...action };
  }
  return state;
}
function RoleSet({ auth }) {
  const [form] = Form.useForm();
  const [state, dispatch] = useReducer(adminRedcuer, initState);
  const onFinish = (values) => {
    const { roleName } = values;
    if (state.data[roleName]) {
      message.error("已经有了该配置");
      return;
    }
    dispatch({
      isModalOpen: false,
      data: {
        ...state.data,
        [roleName]: JSON.parse(JSON.stringify(config.normal)),
      },
    });
    console.log(state.data[roleName]);
    setSetting(
      { title: roleName, content: JSON.stringify(config.normal) },
      (res) => {
        message.success("保存成功");
      }
    );
  };
  //del角色按钮
  const confirm = (rol) => {
    const { data } = state;
    delete data[rol];
    delRole({ title: rol }, (res) => {
      message.success("删除成功");
    });
    dispatch({
      data: { ...data },
    });
  };
  //点击复选框的事件
  const handleChange = (e, item, key, threekey) => {
    const { data } = state;
    data[item][key][threekey].value = e.target.checked;
    dispatch({ data: { ...data } });
    console.log(state.data);
  };
  // 初始化的角色
  const init = () => {
    getSetting({ title: "role" }, (res) => {
      let data = res.data[0].data;
      if (data.length > 0) {
        let o = {};
        data.forEach((item) => {
          if (item.content === null) {
            item.content = config.normal;
            console.log(item.content);
          }
          // o[item.title] = item.content = JSON.parse(item.content);
          o[item.title] =
            item.content !== string ? item.content : JSON.parse(item.content);
        });
        dispatch({
          data: o,
        });
        console.log(o);
        return;
      }
      dispatch({
        data: config,
      });
    });
  };
  useEffect(function () {
    init();
  }, []);
  // 添加角色
  const addAdmin = () => {
    dispatch({
      isModalOpen: true,
    });
    form.setFieldsValue({
      roleName: "",
    });
  };
  // 更新用户的配置信息
  const onUpdate = (role) => {
    const { data } = state;
    updateRole({ title: role, content: JSON.stringify(data[role]) }, (res) => {
      message.success("更新成功");
      console.log(res);
    });
  };
  let data = Object.keys(state.data).map((item, index) => {
    let o = {
      title: (
        <Fragment>
          {item}{" "}
          {auth["/roleset"].update?.value && (
            <CopyOutlined onClick={() => onUpdate(item)} />
          )}
          <Popconfirm title="确认删除" onConfirm={() => confirm(item)}>
            {auth["/roleset"].del?.value && <DeleteOutlined />}
          </Popconfirm>
        </Fragment>
      ),
      key: index,
      children: [],
    };
    o.children = Object.keys(state.data[item]).map((key, j) => {
      let secondO = {
        title: "",
        key: `${index}-${j}`,
      };
      let thtArr = [];
      Object.keys(state.data[item][key]).forEach((threekey, k) => {
        let DatatS = state.data[item][key][threekey];
        if (threekey !== "title") {
          thtArr.push(
            <span key={`${index}-${j}-${k}`} style={{ marginLeft: "15px" }}>
              {DatatS.title}
              <Checkbox
                onChange={(e) => handleChange(e, item, key, threekey)}
                checked={DatatS.value}
                style={{ marginLeft: "5px" }}
              />
            </span>
          );
        }
      });
      secondO.title = (
        <Fragment>
          {state.data[item][key].title}
          <span>{thtArr}</span>
        </Fragment>
      );
      return secondO;
    });
    return o;
  });

  // console.log(data);
  const hiddlen = () => {
    dispatch({
      isModalOpen: false,
    });
  };
  return (
    <Fragment>
      <p>
        {auth["/roleset"].add?.value && (
          <Button type="primary" size="large" onClick={addAdmin}>
            添加
          </Button>
        )}
      </p>
      <Tree showLine switcherIcon={<DownOutlined />} treeData={data} />
      <Modal
        title="添加角色"
        open={state.isModalOpen}
        centered={true}
        footer={null}
        closable={false}
      >
        <Form
          name="basic"
          className={styles.Form}
          initialValues={{
            remember: true,
          }}
          onFinish={onFinish}
          autoComplete="off"
          form={form}
        >
          <Form.Item
            style={{ marginTop: "25px", marginBottom: "25px" }}
            name="roleName"
            rules={[
              {
                required: true,
                message: "请填写姓名",
              },
            ]}
          >
            <Input placeholder="填写你要添加角色的名字" />
          </Form.Item>

          <Form.Item>
            {" "}
            <Row>
              <Col offset={7}>
                <Button type="primary" htmlType="submit">
                  确认
                </Button>{" "}
              </Col>
              <Col offset={2}>
                <Button type="primary" htmlType="button" onClick={hiddlen}>
                  取消
                </Button>{" "}
              </Col>
            </Row>
          </Form.Item>
        </Form>
      </Modal>
    </Fragment>
  );
}
export default connect((state) => {
  let auth = {};
  if (state.user?.roleAuthority) {
    auth = JSON.parse(state.user.roleAuthority);
  }
  return { auth };
})(RoleSet);
